// 配置文件获取

import { bootstrapBefore } from "configs/bootstrap";
import { ENVS } from "./envs";
import development, { EnvRecord } from "./development";
import production from "./production";
import staging from "./staging";
// 拿到配置文件内容
const parsedEnvs = bootstrapBefore();

// 得到当前环境变量
const getCurrentEnv = (): ENVS=>{
    const env = process.env?.ENV;
    if (typeof env === 'undefined') {
        console.error("读取环境变量env失败")
    }
    // 大写转换
    const upperCaseEnv = `${env}`.toUpperCase();
    if (upperCaseEnv === ENVS.PRODUCTION) return ENVS.PRODUCTION;
    if (upperCaseEnv === ENVS.STAGING) return ENVS.STAGING;
    return ENVS.DEVELOPMENT;
}

// 将配置文件.env中配置项整合到对象中
const getCurrentConstants = (ident: ENVS): EnvRecord => {
    // 开发模式常量
    let constants = development;
    // 默认代码配置,  要用.env中的值覆盖
    const source = ident === ENVS.PRODUCTION ? 
    production : ident === ENVS.STAGING ? staging : development;

    // 遍历dev中所有的配置将，使用.env，process，source值进行覆盖
    Object.keys(development).forEach(key => {
        const sourceValue = source[key];    // 无配置文件，无环境变量，以默认为准
        const processValue = process.env[key];  // 环境变量取值
        const parsedValue = parsedEnvs[key];   // 配置文件取值
        if (typeof sourceValue !== 'undefined') {
            constants[key] = sourceValue;
        }
        if (typeof processValue !== 'undefined') {
            constants[key] = processValue;
        }
        if (typeof parsedValue !== 'undefined') {
            constants[key] = parsedValue;
        }
    })

    return constants;

}

// 导出当前env变量
export const CURRENT_ENV = getCurrentEnv();

export const isProd = ()=> CURRENT_ENV === ENVS.PRODUCTION;

const CONSTANTS = getCurrentConstants(CURRENT_ENV);


export default CONSTANTS